package com.ruima.study.arithmetic.sortdemo;

/**
 * <p>
 * <p></p>
 * <p>
 * <p>Copyright (c) 2024/11/19 10:58, 科大讯飞 All Rights Reserve</p>
 *
 * @author ruima6
 * @version [V1.0]
 */
public class MergerSort {
    public void merge1(int[] arr, int left, int right) {
        if (left < right) {
            int mid = (left + right) / 2;
            merge1(arr, left, mid);
            merge1(arr, mid + 1, right);
        }
    }

    public void doMerger(int[] arr, int left, int mid, int right) {
        int[] tempArr = new int[right - left + 1];
        int i = left;
        int j = mid + 1;
        int k = 0;

        while (i <= mid && j <= right) {
            if (arr[i] < arr[j]) {
                arr[k] = arr[left + i];
                i++;
            } else {
                arr[k] = arr[mid + j + 1];
                j++;
            }
            k++;
        }

        while (i <= mid){
            tempArr[k] = arr[left + i];
            i++;
        }

        while (j < right){
            tempArr[k] = arr[mid + j + 1];
            j++;
        }

    }


    public static void main(String[] args) {
        int[] array = {12, 11, 13, 5, 6, 7};
        mergeSort(array, 0, array.length - 1);
        System.out.println("Sorted array: ");
        for (int i : array) {
            System.out.println(i + " ");
        }
    }

    // 归并排序函数
    public static void mergeSort(int[] array, int left, int right) {
        if (left < right) {
            // 找到中间点
            int mid = (left + right) / 2;

            // 对左半部分进行递归排序
            mergeSort(array, left, mid);
            // 对右半部分进行递归排序
            mergeSort(array, mid + 1, right);

            // 合并两个已排序的部分
            merge(array, left, mid, right);
        }
    }

    // 合并函数
    public static void merge(int[] array, int left, int mid, int right) {
        // 计算两个子数组的长度
        int n1 = mid - left + 1;
        int n2 = right - mid;

        // 创建临时数组
        int[] L = new int[n1];
        int[] R = new int[n2];

        // 拷贝数据到临时数组
        for (int i = 0; i < n1; ++i)
            L[i] = array[left + i];
        for (int j = 0; j < n2; ++j)
            R[j] = array[mid + 1 + j];

        // 合并临时数组
        int i = 0, j = 0;
        int k = left;
        while (i < n1 && j < n2) {
            if (L[i] <= R[j]) {
                array[k] = L[i];
                i++;
            } else {
                array[k] = R[j];
                j++;
            }
            k++;
        }

        // 复制剩余的元素
        while (i < n1) {
            array[k] = L[i];
            i++;
            k++;
        }

        while (j < n2) {
            array[k] = R[j];
            j++;
            k++;
        }
    }


}
